package com.lagou.controller;

import com.lagou.bean.Result;
import com.lagou.pojo.OrderDetail;
import com.lagou.service.OrderService;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.UUID;

/**
 * @author: ys
 */
@RestController
public class PayController {

    @Autowired
    private AmqpTemplate rabbitTemplate;

    @Autowired
    OrderService orderService;

    public static Integer count = 1;

    @RequestMapping("/makeOrder")
    public Result makeOrder() {
        OrderDetail order = new OrderDetail();
        UUID uuid = UUID.randomUUID();
        String orderCode = uuid.toString().replaceAll("-", "");
        order.setOrderCode(orderCode);
        order.setCreated(new Date());
        order.setIsPay(0);
        order.setStatus(0);
        order.setName("订单 " + count++);
        rabbitTemplate.convertAndSend("ex.go", "go", orderCode);
        OrderDetail orderDetail = orderService.saveOrUpdate(order);
        return Result.ok(orderDetail);
    }

    @RequestMapping("/pay")
    public Result payOrder(@RequestParam("orderCode")String orderCode) {
        OrderDetail orderDetail = orderService.findByOrderCode(orderCode);
        if(orderDetail == null){
            System.err.println("orderCode  未查询到相应订单=>>>>>>  " + orderCode);
            return Result.error("未查询到订单");
        }
        //订单已支付
        if(orderDetail.getIsPay() == 1){
            return Result.error("订单已支付");
        }
        //订单已支付
        if(orderDetail.getStatus() == 1){
            return Result.error("订单已超时");
        }
        //订单已支付
        orderDetail.setIsPay(1);
        //订单未超时
        orderDetail.setStatus(0);
        orderDetail.setModified(new Date());
        orderService.saveOrUpdate(orderDetail);
        return Result.ok(orderDetail);
    }


    @RequestMapping("/findAll")
    public Result findAll() {
        Page<OrderDetail> all = orderService.findAll(0, 100000);
        return Result.ok(all.getContent());
    }

    @RequestMapping("/notgo")
    public String getAccumulatedTask() {
        String notGo = (String)
                rabbitTemplate.receiveAndConvert("q.go.dlx");
        return notGo;
    }

}
